#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2 as urllib
from BeautifulSoup import BeautifulSoup as bs
import sys
import os
import MySQLdb

QUERY = sys.argv[1]

def createUrl(lang_from, lang_to, query):
    url = "http://langtolang.com/?selectFrom=%s&selectTo=%s&txtLang=%s" %(lang_from, lang_to, query)
    return url

def getPage(url):
    page = urllib.urlopen(url)
    page = page.read()
    return page

def getList(html):
    trans_list = []
    soup = bs(html)
    soup = soup.find("div", attrs={"id" : "mainContent"})
    soup = soup.findAll("table")
    soup = soup[1]
    soup = soup.findAll("tr")
    for s in soup:
        s = s.findAll("td")
        try:
            trans_list.append(s[1].text.strip())
        except:
            pass

    trans_list.pop(0)
    return trans_list

def getTemplate(query, list_tr, list_en):
    txt_tr = ", ".join(list_tr)
    txt_en = ", ".join(list_en)
    template = " | ".join([query, txt_tr, txt_en])
    template = template.capitalize()
    template = template[0:140]
    last = template.rfind(",")
    template = template.encode("utf-8", "replace")
    return template[0:last]


def save(word, translation):
    try:
        conn = MySQLdb.connect(host="localhost", user="pardus", passwd="", db="spanish")
        cursor = conn.cursor()
        query = "insert into words (word, translation) values ('%s', '%s')" %(word, translation)
        cursor.execute(query)
        conn.commit()
        conn.close()
    except MySQLdb.Error, e:
        print "!!!!!!!!!!!! Error: %s" %e

url_es_tr = createUrl("spanish", "turkish", QUERY)
url_es_en = createUrl("spanish", "english", QUERY)
html_tr = getPage(url_es_tr)
html_en = getPage(url_es_en)
trans_list_tr = getList(html_tr)
trans_list_en = getList(html_en)
template = getTemplate(QUERY, trans_list_tr, trans_list_en)
print ""
print len(template)
print template

question = raw_input("Do you want to save this: ")
if question == "no":
    print "Get out"
else:
    save(QUERY, template)
    print "Saved successfuly.."
